<template>
  <Category :screen="screen"></Category>
  <el-card style="margin: 10px 0">
    <div v-show="screen == 0">
      <el-button
        type="primary"
        icon="Plus"
        :disabled="!categoryStore.thirdCategoryId"
        @click="addAttr"
        v-has="`btn.Trademark.add`"
      >
        添加属性
      </el-button>
      <el-table style="width: 100%; margin: 10px 0" border :data="attrList">
        <el-table-column label="序号" width="80" type="index" align="center" />
        <el-table-column label="属性名" width="180" prop="attrName" />
        <el-table-column label="属性值">
          <template #default="{ row }">
            <el-tag
              style="margin: 5px"
              type="success"
              v-for="item in row.attrValueList"
              :key="item.id"
            >
              {{ item.valueName }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              size="small"
              @click="editAttr(row)"
            ></el-button>

            <el-popconfirm
              :title="`你确认要删除${row.attrName}吗?`"
              width="250px"
              icon="Delete"
              :hide-after="0"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete" size="small"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="screen == 1">
      <el-form inline>
        <el-form-item label="属性名">
          <el-input
            placeholder="请输入属性名"
            v-model="attrParams.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="Plus"
        :disabled="!attrParams.attrName"
        @click="addAttrValue"
      >
        添加属性
      </el-button>
      <el-button @click="cancelAttrValue">取消</el-button>

      <el-table border style="margin: 10px 0" :data="attrParams.attrValueList">
        <el-table-column
          label="序号"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #default="{ row, $index }">
            <el-input
              v-if="row.flag"
              @blur="toLook(row, $index)"
              placeholder="请你输入属性值名称"
              v-model="row.valueName"
              :ref="(vc: any) => (inputArr[$index] = vc)"
            ></el-input>
            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="属性值操作">
          <template #default="{ $index }">
            <el-button
              type="danger"
              icon="Delete"
              size="small"
              @click="deleteAttrValue($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        icon="Plus"
        @click="save"
        :disabled="attrParams.attrValueList.length == 0"
      >
        保存
      </el-button>
      <el-button @click="cancel">关闭</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import Category from '@/components/Category/index.vue'
import useCategoryStore from '@/store/modules/category.ts'
import { nextTick, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { reqAddOrUpdateAttr, reqAttr, reqRemoveAttr } from '@/api/product/attr'
import { Attr, AttrValue } from '@/api/product/attr/type.ts'
import { ElMessage } from 'element-plus'

let categoryStore = useCategoryStore()
let attrList = ref<Attr[]>([])
let screen = ref(0)
//收集新增的属性的数据
let attrParams = reactive<Attr>({
  attrName: '', //新增的属性的名字
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: '', //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
})
//准备一个数组:将来存储对应的组件实例el-input
let inputArr = ref<any>([])
watch(
  () => categoryStore.thirdCategoryId,
  () => {
    if (!categoryStore.thirdCategoryId) return
    getAttrList()
  },
)

async function getAttrList() {
  let { mainCategoryId, secCategoryId, thirdCategoryId } = categoryStore
  let result = await reqAttr(mainCategoryId, secCategoryId, thirdCategoryId)
  if (result.code === 200) {
    attrList.value = result.data
  }
}

function addAttr() {
  // 清空之前的属性
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.thirdCategoryId,
    categoryLevel: 3,
  })
  screen.value = 1
}

function addAttrValue() {
  attrParams.attrValueList.push({ valueName: '', flag: true })
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

function cancelAttrValue() {
  attrParams.attrValueList.pop()
}

function deleteAttrValue(index: number) {
  attrParams.attrValueList.splice(index, 1)
}
function editAttr(row: any) {
  screen.value = 1
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

async function deleteAttr(id: any) {
  // 1.发送请求保存属性
  let result = await reqRemoveAttr(id)
  if (result.code === 200) {
    ElMessage.success('删除属性成功')
    // 2.重新再获取属性列表
    getAttrList()
  } else {
    ElMessage.error('删除属性失败')
  }
}

//属性值表单元素失却焦点事件回调
const toLook = (row: AttrValue, $index: number) => {
  //非法情况判断1
  if (row.valueName.trim() == '') {
    //删除调用对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage.warning('属性值不能为空')
    return
  }
  //非法情况2
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })

  if (repeat) {
    //将重复的属性值从数组当中干掉
    attrParams.attrValueList.splice($index, 1)
    //提示信息
    ElMessage({
      type: 'warning',
      message: '属性值不能重复',
    })
    return
  }
  //相应的属性值对象flag:变为false,展示div
  row.flag = false
}

//属性值div点击事件
const toEdit = (row: AttrValue, $index: number) => {
  //相应的属性值对象flag:变为true,展示input
  row.flag = true
  //nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
function cancel() {
  screen.value = 0
}

async function save() {
  // 1.发送请求保存属性
  let result = await reqAddOrUpdateAttr(attrParams)
  if (result.code === 200) {
    ElMessage.success(attrParams.id ? '修改属性成功' : '新增属性成功')
    // 2.重新再获取属性列表
    getAttrList()
    screen.value = 0
  } else {
    ElMessage.error(attrParams.id ? '修改属性失败' : '新增属性失败')
  }
}

//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  //清空仓库的数据
  categoryStore.$reset()
})
</script>

<style scoped lang="scss"></style>
